package com.zhihong.service.impl;

import com.zhihong.entity.BlogVo;
import com.zhihong.service.BlogService;
import com.zhihong.utils.ExcelExportUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName BlogServiceImpl
 * @Author 庄志宏
 * @Date 2022/8/31 12:35
 */
@Service
public class BlogServiceImpl implements BlogService {
    @Override
    public List<BlogVo> getBlogList() {
        List<BlogVo> list = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        List<String> dateList = new ArrayList<>();
        List<String> viewCountList = new ArrayList<>();
        List<String> pictureList = new ArrayList<>();
        try {
            for (int j=1;j<60;j++){
                Document document = Jsoup.connect("https://www.aquanliang.com/blog/page/" + j).timeout(10000).get();
                Elements e = document.getElementsByClass("_3gcd_TVhABEQqCcXHsrIpT");
                Elements title = e.select("._3HG1uUQ3C2HBEsGwDWY-zw").select("a").select("._3_JaaUmGUCjKZIdiLhqtfr"); //文章标题
                Elements date = e.select("._3HG1uUQ3C2HBEsGwDWY-zw").select("._1nlYtcrR408yNacE0R0s3M").select("._3TzAhzBA-XQQruZs-bwWjE");  //文章发布日期
                Elements viewCount = e.select("._3HG1uUQ3C2HBEsGwDWY-zw").select("._1nlYtcrR408yNacE0R0s3M").select("._2gvAnxa4Xc7IT14d5w8MI1"); //文章阅读数
                Elements picture = e.select("a").select("._1wTUfLBA77F7m-CM6YysS6").select("._3NQyvscVRjQNS9gEgQoDDo").select("._2ahG-zumH-g0nsl6xhsF0s").select("div").select("img"); //文章封面图

                title.forEach(item -> {
                    titleList.add(item.text());
                });
                date.forEach(item -> {
                    dateList.add(item.text());
                });
                viewCount.forEach(item -> {
                    viewCountList.add(item.text());
                });
                picture.forEach(item -> {
                    String src = item.attr("src");
                    pictureList.add(src);
                });

                for (int i = 0; i < titleList.size(); i++) {
                    BlogVo blogVo = new BlogVo();
                    blogVo.setTitle(titleList.get(i));
                    blogVo.setDate(dateList.get(i));
                    blogVo.setViewCount(viewCountList.get(i));
                    blogVo.setPicture(pictureList.get(i));
                    list.add(blogVo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void export(HttpServletResponse httpServletResponse) throws Exception {
        new ExcelExportUtils().export(BlogVo.class, getBlogList(), httpServletResponse, "blog");
    }

}
